import {colorPalette} from './palette.js';
import {hexToRgb,hsvToHex,rgbToHsl,rgbToHsv} from './color.js';

function calculateSaturation(r, g, b) {
	const max = Math.max(r, g, b);
	const min = Math.min(r, g, b);
	if (max === min) {
		return 0;
	}
	return (max - min) / max;
};

/**
 * 暗黑模式动态梯度算法，参考 [Arco Design色彩算法](https://arco.design/palette/list)
 */
export function colorPaletteDark(originColor, i) {
	const lightColor = hexToRgb(colorPalette(originColor, 10 - i + 1));
	const originBaseColor = hexToRgb(originColor);
	const originBaseHue = rgbToHsl(originBaseColor.r, originBaseColor.g, originBaseColor.b).h;
	const originBaseSaturation = calculateSaturation(originBaseColor.r, originBaseColor.g, originBaseColor.b) * 100;

	function baseColorSaturation() {
		if (originBaseHue >= 50 && originBaseHue < 191) {
			return originBaseSaturation - 20;
		} else {
			return originBaseSaturation - 15;
		}
	};

	const baseColor = {
		h: originBaseHue,
		s: baseColorSaturation(),
		v: rgbToHsv(originBaseColor.r, originBaseColor.g, originBaseColor.b).v * 100
	};

	const baseSaturation = baseColor.s;

	const step = Math.ceil((baseSaturation - 9) / 4);
	const step1to5 = Math.ceil((100 - baseSaturation) / 5);

	function getNewSaturation(_index) {
		if (_index < 6) {
			return baseSaturation + (6 - _index) * step1to5;
		} else if (_index == 6) {
			if (originBaseHue >= 50 && originBaseHue < 191) {
				return originBaseSaturation - 20;
			} else {
				return originBaseSaturation - 15;
			}
		} else {
			return baseSaturation - step * (_index - 6);
		}
	};

	const retColor = hsvToHex(
		rgbToHsv(lightColor.r, lightColor.g, lightColor.b).h,
		getNewSaturation(i) / 100,
		rgbToHsv(lightColor.r, lightColor.g, lightColor.b).v
	);

	return retColor;
};